package top.lshaci.learning.gateway.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;

/**
 * ApiPrefixFilter
 *
 * @author lshaci
 * @date 2020/9/25 13:42
 * @since 1.0.0
 */
public class ApiPrefixFilter implements WebFilter {

    @Value("${spring.cloud.gateway.api-prefix:/api}")
    private String prefix;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        addOriginalRequestUrl(exchange, request.getURI());
        String path = request.getURI().getRawPath();
        if (!path.contains(prefix)) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.BAD_GATEWAY);
            DataBuffer dataBuffer = response.bufferFactory()
                    .wrap(HttpStatus.BAD_GATEWAY.getReasonPhrase().getBytes());
            return response.writeWith(Mono.just(dataBuffer));
        }
        String newPath = path.replaceFirst(prefix, "");
        ServerHttpRequest newRequest = request.mutate().path(newPath).build();
        exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());
        return chain.filter(exchange.mutate().request(newRequest).build());
    }
}
